﻿using ProjectScheduling.daos;
using ProjectScheduling.models;

namespace ProjectScheduling
{
    public partial class LoginForm : Form
    {
        public static readonly LoginForm b = new();
        public LoginForm()
        {
            InitializeComponent();
            if (Program.LoginUser != null)
            {
                new MainForm().ShowDialog();
                Close();
            }
            var data = Common.ReadFile<RemindLoginStatecs>("loginState", true) ?? new();
            checkBox1.Checked = data.IsRemind;
            if (data.IsRemind)
            {
                txt_username.Text = data.UserName;
                txt_password.Text = data.Password;
            }
        }

        private void Btn_login_Click(object sender, EventArgs e)
        {
            var username = txt_username.Text?.Trim() ?? "";
            var password = txt_password.Text?.Trim() ?? "";
            var safe = Common.Md5(password);
            var userMsg = UsersDao.Base.Find(it => !string.IsNullOrEmpty(it.Name) && !string.IsNullOrEmpty(it.Password) && it.Name.Equals(username) && it.Password.Equals(safe));
            if (userMsg == null)
            {
                MessageBox.Show("用户名或者密码有误", "登录错误");
                return;
            }
            if (checkBox1.Checked)
            {

            }
            Common.WriteFile("loginState", new RemindLoginStatecs(checkBox1.Checked, username, password), true);
            Program.LoginUser = userMsg;
            Hide();
            Program.ShowFormDialog(MainForm.b);
        }

        private void LoginForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void txt_password_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                Btn_login_Click(sender, e);
            }
        }
    }
}
